#include <libseminix/seminix.h>
#include <utils/pagesize.h>
#include <utils/atomic.h>
#include <pthread.h>

static atomic_t test;
static char thread2_stack[UTILS_PAGE_SIZE];
static char thread3_stack[UTILS_PAGE_SIZE];

static pthread_spinlock_t lock;

static __thread uint64_t per_thread_var_test = 5;

static void *test_thread(void *arg);

static void *test_thread2(void *arg)
{
    while (1) {
        printf("now 2 thread %ld\n", per_thread_var_test);
        per_thread_var_test += 6;
        seminix_yield();
    }
    return NULL;
}

int main(int argc, const char *argv[])
{
    int tcb, ret;
    seminix_object_t obj;
    tcb_config_t config;
    pthread_t pthread1, pthread2;
    pthread_attr_t attr1, attr2;

    printf("hello root service => argv: %s\n", argv[0]);
    pthread_spin_init(&lock, 0);
    obj.type = seminix_TcbObject;
    tcb = seminix_createrlimit(seminix_all_rights, &obj);
    printf("create tcb %d\n", tcb);
    config.vspace = 196608;
    ret = seminix_tcb_configure(tcb, TCB_CONFIG_VSPACE, &config);
    printf("config vspace %d\n", ret);

    pthread_attr_init(&attr1);
    pthread_attr_setstack(&attr1, thread2_stack, UTILS_PAGE_SIZE);
    seminix_set_mr(0, tcb);
    ret = pthread_create(&pthread1, &attr1, test_thread, NULL);
    printf("ssssssssss\n");


    obj.type = seminix_TcbObject;
    tcb = seminix_createrlimit(seminix_all_rights, &obj);
    printf("create tcb %d\n", tcb);
    config.vspace = 196608;
    ret = seminix_tcb_configure(tcb, TCB_CONFIG_VSPACE, &config);
    printf("config vspace %d\n", ret);

    pthread_attr_init(&attr2);
    pthread_attr_setstack(&attr2, thread3_stack, UTILS_PAGE_SIZE);
    seminix_set_mr(0, tcb);
    ret = pthread_create(&pthread2, &attr2, test_thread2, NULL);
    assert(!ret);
    atomic_set(&test, 1);
    while (1) {
        //pthread_spin_lock(&lock);
        printf("now main thread! %ld\n", per_thread_var_test++);
        //pthread_spin_unlock(&lock);
        seminix_yield();
    }

    return 0;
}

static void *test_thread(void *arg)
{
    while (1) {
        printf("start test thread %ld\n", per_thread_var_test--);
        seminix_yield();
    }
    return NULL;
}
